package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitmqConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;


@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @param eventType 当前操作数据库的类型
     * @param rowData   当前操作数据库的数据
     * @return void
     * @description:
     * @author 大佬味的小男孩
     * @date 2020/07/22 11:11
     */
    @ListenPoint(schema = "changgou_goods", table = {"tb_spu"}, eventType = CanalEntry.EventType.UPDATE)
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.err.println("tb_spu表的数据发生变化");

        //修改前数据
        Map oldMap = new HashMap<>();
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            oldMap.put(column.getName(), column.getValue());
        }

        //修改后数据
        Map newMap = new HashMap<>();
        for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
            newMap.put(column.getName(), column.getValue());
        }

        //is_marketable  由0改为1表示上架
        // 如果满足在修改前上架状态为0并且在修改数据后上架状态为1
        if ("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable"))) {
            //将spu商品的id消息发送到rabbitmq
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_UP_EXCHANGE, "", newMap.get("id"));
        }

        //is_marketable  由1改为0表示下架
        // 如果满足在修改前上架状态为1并且在修改数据后上架状态为0
        if ("1".equals(oldMap.get("is_marketable")) && "0".equals(newMap.get("is_marketable"))) {
            //将spu商品的id消息发送到rabbitmq
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_DOWN_EXCHANGE, "", newMap.get("id"));
        }

        //status 从0到1 代表审核通过
        if ("0".equals(oldMap.get("status")) &&"1".equals(newMap.get("status"))){
            //将spu商品的id消息发送到rabbitmq
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_UP_EXCHANGE,"",newMap.get("id"));
        }


    }
}
